<?php

class umFormular{
	const FORM_HASH_NAME = "umHash";
	
	private static $instance;
	public static function getInstance(){
		if(empty(self::$instance)){
			self::$instance = new self($_POST);
		}
		
		return self::$instance;
	}

	private $next_hash;
	private $current_hash;
	
	private $data;
	
	private function __construct($POST){
		$this->data = $POST;
		
		$this->current_hash = !empty($_SESSION[self::FORM_HASH_NAME])?$_SESSION[self::FORM_HASH_NAME]:null;
		
		$this->next_hash = $this->generateNextHash();
		$_SESSION[self::FORM_HASH_NAME] = $this->next_hash;
	}
	
	/**
	 * get the hash name
	 * 
	 * @return string
	 */
	public function getHashName(){
		return self::FORM_HASH_NAME;
	}
	
	/**
	 * generate a new hash
	 * 
	 * @return string
	 */
	private function generateNextHash(){
		$t = crypt(rand(100000, 9999999999), microtime(true));
		return sha1($t);
	}
	
	/**
	 * check if the submission is invalid
	 * 
	 * @return bool
	 */
	public function isInvalidForm(){
		if(empty($this->data[self::FORM_HASH_NAME])){
			return false;
		}
		
		if(empty($this->current_hash)){
			return true;
		}
		
		if($this->data[self::FORM_HASH_NAME]==$this->current_hash){
			return false;
		}
		
		return true;
	}
	
	/**
	 * check if the submission is a valid form
	 * 
	 * @return bool
	 */
	public function isValidForm(){
		if(empty($this->data[self::FORM_HASH_NAME])){
			return false;
		}
		
		if(empty($this->current_hash)){
			return false;
		}
		
		if($this->data[self::FORM_HASH_NAME]==$this->current_hash){
			return true;
		}
		
		return false;
	}
	
	/**
	 * get hash value
	 * 
	 * @return string
	 */
	public function getHash(){
		return $this->next_hash;
	}
	
	public function getInt($name){
		return (int)$this->getVariable($name);
	}
	
	public function getString($name){
		return (string)$this->getVariable($name);
	}
	
	public function getFloat($name){
		return (float)$this->getVariable($name);
	}
	
	public function getVariable($name){
		if(isset($this->data[$name])){
			return $this->data[$name];
		}
		
		return null;
	}
}
